package javaagent.jvmtool;

import com.sun.tools.attach.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author zzs
 */
public class AttachStart {
    public static void main(String[] args) throws Exception {
        // 获取jvm进程列表 借用tool工具实现进程交互
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(String.format("[%s] %s", i, list.get(i).displayName()));
        }
        System.out.println("输入数字指定要attach的进程");

        // 选择jvm进程
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        String line = read.readLine();
        int i = Integer.parseInt(line);
        // 附着agent
        VirtualMachine virtualMachine = VirtualMachine.attach(list.get(i));
        // 将对应的agent功能附着到指定进程进去实现运行时启动
        virtualMachine.loadAgent("E:/javaCode/javaagent/target/javaagent-1.0-SNAPSHOT.jar", "111");
        virtualMachine.detach();
        System.out.println("加载成功");
    }
}